package com.itlaobing.test;

import javax.sound.midi.Soundbank;
import java.util.Random;
import java.util.concurrent.*;

public class ThreadTest1 {

    private static class MyThread extends Thread{//继承Thread
        @Override
        public void run() {
//            线程体（需要新创建的线程中执行的任务，可以写在这里）
            for (int i = 0; i <1000 ; i++) {
                System.out.println("副线程执行："+i);
            }
        }
    }

    private static class MyRun implements Runnable{//实现Runnable接口

        @Override
        public void run() {
            for (int i = 0; i <1000 ; i++) {
                System.out.println("MyRun副线程执行："+i);
            }
        }
    }

    private static class MyCall implements Callable<Integer> {
//        Callable接口中的call方法,是具有返回值的。所以适合于需要用返回值的线程任务
        @Override
        public Integer call() throws Exception {
            for (int i = 0; i <1000 ; i++) {
                System.out.println("MyCall副线程执行："+i);
            }
            return new Random().nextInt(1000);
        }
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
          testMyThread();
//        testMyRun();
        testMyCall();
        testThreadPool();
        for (int i = 0; i <1000 ; i++) {
            System.out.println("主线程执行："+i);
        }
        System.exit(0);//强制退出，关闭所有的线程
    }

    private static void testThreadPool() throws ExecutionException, InterruptedException {
//        ExecutorService executorService=new ThreadPoolExecutor();
//        ExecutorService executorService=Executors.newSingleThreadExecutor();
        ExecutorService executorService=Executors.newFixedThreadPool(5);
        MyCall myCall=new MyCall();
        Future<Integer> future = executorService.submit(myCall);
        Future<Integer> future1 = executorService.submit(myCall);
        System.out.println(future.get());
}

    private static void testMyCall() throws ExecutionException, InterruptedException, TimeoutException {
        MyCall myCall=new MyCall();
        FutureTask<Integer> futureTask=new FutureTask<>(myCall);
        new Thread(futureTask).start();
        System.out.println(futureTask.get(1000, TimeUnit.MILLISECONDS));
    }

    private static void testMyRun() {
        MyRun myRun=new MyRun();
        new Thread(myRun).start();//最爱问启动方式
    }

    private static void testMyThread() {
        MyThread myThread=new MyThread();
//        myThread.run();//虽然可以执行，但是没有多线程并行运算的效果
        System.out.println(myThread.getState());
        myThread.start();
    }
}
